package com.asiainfo.system.management.service.impl;

import com.asiainfo.common.constants.UserConstants;
import com.asiainfo.common.exception.businessException.BusinessException;
import com.asiainfo.common.utils.StringUtils;
import com.asiainfo.framework.utils.MD5Utils;
import com.asiainfo.framework.web.page.PageResult;
import com.asiainfo.framework.web.page.Pagination;
import com.asiainfo.system.management.domain.model.SysUser;
import com.asiainfo.system.management.domain.model.SysUserPost;
import com.asiainfo.system.management.domain.model.SysUserRole;
import com.asiainfo.system.management.service.SysUserService;
import com.asiainfo.system.management.shiro.utils.ShiroUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户 业务层处理
 */
@Service
public class SysUserServiceImpl extends SystemManagementBaseService implements SysUserService {

    @Override
    public SysUser findUserByUserName(String username) {
        return dao.selectOne("SysMgr.SysUser.findUserByUserName", username);
    }

    @Override
    public SysUser login(String username, String password) {
        SysUser user = dao.selectOne("SysMgr.SysUser.findUserByUserName", username);
        if (user == null) {
            throw new BusinessException("登录失败，用户不存在！");
        }
        return ShiroUtils.matches(user, password) ? user : null;
    }

    @Override
    public PageResult<SysUser> selectUserList(Pagination page, SysUser user) {
        return dao.selectList("SysMgr.SysUser.selectUserList", user, page);
    }

    @Override
    public List<SysUser> selectUserList(SysUser user) {
        return dao.selectList("SysMgr.SysUser.selectUserList", user);
    }


    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean updateUser(SysUser user) {
        //重新给定权限
        dao.delete("SysMgr.SysUserRole.deleteUserRoleByUserId", user.getId());
        batchUserRole(user);
        // 删除用户与岗位关联
        dao.delete("SysMgr.SysUserRole.deleteUserPostByUserId", user.getId());
        // 新增用户与岗位管理
        batchUserPost(user);
        return dao.update("SysMgr.SysUser.updateUser", user) > 0;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean updateUserLoginInfo(SysUser user) {
        return dao.update("SysMgr.SysUser.updateUser", user) > 0;
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    private boolean batchUserPost(SysUser user) {
        int rows = 1;
        // 新增用户与岗位管理
        List<SysUserPost> list = new ArrayList<>();

        if (user.getPostIds() != null && user.getPostIds().size() > 0) {
            user.getPostIds().forEach(postId -> {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getId());
                up.setPostId(postId);
                list.add(up);
            });

            if (list.size() > 0) {
                rows = dao.insert("SysMgr.SysUserPost.batchUserPost", list);
            }
        }
        return rows > 0;
    }

    private boolean batchUserRole(SysUser user) {
        int rows = 1;
        List<SysUserRole> list = new ArrayList<>();
        if (user.getRoleIds() != null && user.getRoleIds().size() > 0) {
            user.getRoleIds().forEach(roleId -> {
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(user.getId());
                list.add(userRole);
            });
        }
        if (list.size() > 0) {
            rows = dao.insert("SysMgr.SysUser.batchUserRole", list);
        }
        return rows > 0;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean insertUser(SysUser user) {
        user.setSalt(MD5Utils.randomSalt());
        user.setPassword(MD5Utils.encryptPassword(user.getUserName(), user.getPassword(), user.getSalt()));
        return dao.insert("SysMgr.SysUser.insertUser", user) > 0 && batchUserRole(user) && batchUserPost(user);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean deleteUserById(Long id) {
        return true;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean deleteUserByIds(Long[] ids) {
        for (Long userId : ids) {
            if (SysUser.isAdmin(userId)) {
                throw new BusinessException("不允许删除超级管理员用户");
            }
        }
        return dao.delete("SysMgr.SysUser.deleteUserByIds", ids) > 0;
    }

    @Override
    public SysUser selectUserById(Long id) {
        return dao.selectOne("selectUserById", id);
    }

    @Override
    public SysUser selectUserByIdAndDept(Long id) {
        return dao.selectOne("selectUserByIdAndDept", id);
    }

    /**
     * 修改用户个人详细信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean updateUserInfo(SysUser user) {
        return dao.update("SysMgr.SysUser.updateUser", user) > 0;
    }

    /**
     * 修改用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean modifyPassword(SysUser user, String oldPassWord, String newPassword) {
        if (ShiroUtils.matches(user, oldPassWord)) {//验证旧密码是否正确
            user.setSalt(MD5Utils.randomSalt());
            user.setPassword(MD5Utils.encryptPassword(user.getUserName(), newPassword, user.getSalt()));
            return updateUserInfo(user);
        }
        throw new BusinessException("旧密码不正确！");
    }

    @Override
    public boolean resetUserPwd(Long userId, String newPassword) {
        SysUser user = dao.selectOne("selectUserById", userId);
        user.setSalt(MD5Utils.randomSalt());
        user.setPassword(MD5Utils.encryptPassword(user.getUserName(), newPassword, user.getSalt()));
        return updateUserInfo(user);
    }


    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(SysUser user) {
        long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        List<SysUser> userList = dao.selectList("SysMgr.SysUser.checkUserNameUnique", user.getUserName());
        if (userList != null) {
            for (SysUser sysUser : userList) {
                if (StringUtils.isNotNull(sysUser) && sysUser.getId() != userId) {
                    return UserConstants.USER_PHONE_NOT_UNIQUE;
                }
            }
        }
        return UserConstants.USER_NAME_UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        List<SysUser> userList = dao.selectList("SysMgr.SysUser.checkPhoneUnique", user.getPhoneNumber());
        if (userList != null) {
            for (SysUser sysUser : userList) {
                if (StringUtils.isNotNull(sysUser) && sysUser.getId() != userId) {
                    return UserConstants.USER_PHONE_NOT_UNIQUE;
                }
            }
        }
        return UserConstants.USER_PHONE_UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        List<SysUser> userList = dao.selectList("SysMgr.SysUser.checkEmailUnique", user.getEmail());
        if (userList != null) {
            for (SysUser sysUser : userList) {
                if (StringUtils.isNotNull(sysUser) && sysUser.getId() != userId) {
                    return UserConstants.USER_EMAIL_NOT_UNIQUE;
                }
            }
        }
        return UserConstants.USER_EMAIL_UNIQUE;
    }
}
